package com.canbot.u05.activity.editmodule;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.IndustryModActivity;
import com.canbot.u05.activity.vipguide.ReceptionSettingActivity;
import com.canbot.u05.bean.AppInfo;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import okhttp3.ResponseBody;

public class EditModuleActivity extends BaseActivityNoTitle {
    private final String TAG = this.getClass().getSimpleName();

    private RecyclerView selectRecycleView;
    private RecyclerView unSelectRecycleView;
    private AppInfoSelctAdapter appInfoSelctAdapter;
    private AppInfoUnSelctAdapter appInfoUnSelctAdapter;
    private TextView ivEditCompleted;
    private ArrayList<AppInfo> unSelectModules;
    private ArrayList<AppInfo> selectModules;
    private boolean isSorted = false; //是否拖动图标排序
    private ToastTools toastTools;
    private String jsonDatas;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_edit_module);

        toastTools = ToastTools.newInstance(this);
        selectModules = new ArrayList();
        unSelectModules = new ArrayList();

        selectRecycleView = findViewById(R.id.rv_select);
        unSelectRecycleView = findViewById(R.id.rv_unselect);
        ivEditCompleted = (TextView) findViewById(R.id.edit_modules_completed);

        HorizontalLinearLayoutManager layoutManager= new HorizontalLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        selectRecycleView.setLayoutManager(layoutManager);
        selectRecycleView.addItemDecoration(new SpacesItemDecoration(10));
        appInfoSelctAdapter = new AppInfoSelctAdapter(this, selectModules,R.layout.item_module_minus);
        selectRecycleView.setAdapter(appInfoSelctAdapter);
        helper.attachToRecyclerView(selectRecycleView);

        HorizontalLinearLayoutManager layoutManager2= new HorizontalLinearLayoutManager(this);
        layoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        unSelectRecycleView.setLayoutManager(layoutManager2);
        unSelectRecycleView.addItemDecoration(new SpacesItemDecoration(10));
        appInfoUnSelctAdapter = new AppInfoUnSelctAdapter(this, unSelectModules,R.layout.item_module_add);
        unSelectRecycleView.setAdapter(appInfoUnSelctAdapter);

        appInfoUnSelctAdapter.setSelectAdapter(appInfoSelctAdapter);
        appInfoSelctAdapter.setUnselectAdapter(appInfoUnSelctAdapter);

        initData();

        ivEditCompleted.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList allAppInfos = appInfoSelctAdapter.getAllAppInfos();

                String jsonString = JSON.toJSONString(allAppInfos);

                if (!isSorted && !appInfoSelctAdapter.hasEdit()){
                    toastTools.showText("功能未改动");
                    return;
                }

                upLoadAppInfos(jsonString);
            }
        });

        selectRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == ItemTouchHelper.ACTION_STATE_IDLE){


                }else if (newState == ItemTouchHelper.ACTION_STATE_IDLE){


                }
            }
        });

    }

    /**
     * 上传APP修改信息到胸口
     * @param jsonString
     */
    private void upLoadAppInfos(String jsonString) {

        dialogLoading = LoadingDialogUtils.createLoadingDialog(EditModuleActivity.this, getResources().getString(R.string.data_upload));

        ArrayList allAppInfos = appInfoSelctAdapter.getAllAppInfos();
        String jsonStr = JSON.toJSONString(allAppInfos);

        HashMap<String, Object> hasMap = new HashMap<>();
        hasMap.put("edit_list",jsonStr);

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "appInfo", hasMap, new OkHttpUtils.OkHttpCallBack() {
            @Override
            public void onSuccess(String result) {
                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                if (strMsgBean.getRc() == 0){
                    toastTools.showText("更新成功");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    cancelDialog();

                                    startActivity(new Intent(EditModuleActivity.this,IndustryModActivity.class));

                                    finish();
                                }
                            });

                        }
                    });
                }else{

                    toastTools.showText("更新失败");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cancelDialog();
                        }
                    });

                }

            }

            @Override
            public void onFailure() {
                toastTools.showText("服务器异常,请重试!");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        cancelDialog();
                    }
                });
            }
        });
    }

    /**
     * 取消加载的Dialog
     */
    private void cancelDialog() {
        if (dialogLoading != null) {
            if (dialogLoading.isShowing()) {
                dialogLoading.cancel();
            }
        }
    }



    public void back(View view){
        startActivity(new Intent(this, IndustryModActivity.class));

        finish();
    }


    private void initData() {

        requestAppInfo();

    }

    private void requestAppInfo() {

        dialogLoading = LoadingDialogUtils.createLoadingDialog(EditModuleActivity.this, getResources().getString(R.string.request));

        HashMap<String, Object> hasMap = new HashMap<>();
        hasMap.put("get_data","get_data");

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "appInfo", hasMap, new OkHttpUtils.OkHttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG,"success ： " + result);

                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                if (strMsgBean.getRc() == 0){

                    Log.e(TAG,"success ： 获取数据成功");
                    String  str = strMsgBean.getResult().toString();
                    List<AppInfo> appInfos = JSON.parseArray(str, AppInfo.class);
                    splitAppInfos(appInfos);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cancelDialog();
                        }
                    });


                }else{
                    toastTools.showText("获取数据失败");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cancelDialog();
                        }
                    });
                }


            }

            @Override
            public void onFailure() {
                toastTools.showText("服务器异常,请重试!");
                Log.e(TAG,"getData onFailure");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        cancelDialog();
                    }
                });
            }
        });
    }


    /**
     * 分离数据
     * @param appInfos
     */
    private void splitAppInfos(List<AppInfo> appInfos) {
        selectModules.clear();
        unSelectModules.clear();

        for (int i = 0; i < appInfos.size(); i++) {
            AppInfo appInfo = appInfos.get(i);
            if (appInfo.isMainFunction()){
                selectModules.add(appInfo);
            }else{
                unSelectModules.add(appInfo);
            }
        }

        if (selectModules.size() > 1){
            Collections.sort(selectModules, new Comparator<AppInfo>() {
                @Override
                public int compare(AppInfo o1, AppInfo o2) {
                    return o1.getPosition() - o2.getPosition();
                }
            });
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                appInfoSelctAdapter.setDatas(selectModules);
                appInfoUnSelctAdapter.setDatas(unSelectModules);
            }
        });


    }


    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        //线性布局和网格布局都可以使用
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFrlg = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager){
                dragFrlg = ItemTouchHelper.UP| ItemTouchHelper.DOWN| ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT;
            }else if(recyclerView.getLayoutManager() instanceof LinearLayoutManager){
                dragFrlg = ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT;
            }
            return makeMovementFlags(dragFrlg,0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(selectModules, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(selectModules, i, i - 1);
                }
            }

            appInfoSelctAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
              //侧滑删除可以使用；
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }
        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {

                viewHolder.itemView.setBackgroundResource(R.drawable.shape_item_moudle_bg_drag);
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundResource(R.drawable.shape_item_moudle_bg_nor);
            appInfoSelctAdapter.notifyDataSetChanged();  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
            isSorted = true;
        }
    });

}
